package com.erp.produce.service.impl;

import com.alibaba.fastjson.JSON;
import com.erp.common.util.ServiceUtil;
import com.erp.common.util.StringUtil;
import com.erp.produce.dao.OrderDao;
import com.erp.produce.dao.ProductionTaskDao;
import com.erp.produce.dao.ProductionTechnologyDao;
import com.erp.produce.dto.GoodsInfo;
import com.erp.produce.dto.ProductionTechnologyDTO;
import com.erp.produce.entity.Order;
import com.erp.produce.entity.ProductionTask;
import com.erp.produce.mapper.OrderMapper;
import com.erp.produce.service.OrderService;

import com.erp.stock.dao.RawMaterialDao;
import com.erp.stock.dao.RawMaterialInventoryDao;
import com.erp.stock.entity.RawMaterial;
import com.erp.stock.entity.RawMaterialInventory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductionTechnologyDao ptDao;

    @Autowired
    private RawMaterialInventoryDao rawMaterialInventoryDao;

    @Autowired
    private RawMaterialDao rawMaterialDao;

    @Autowired
    private ProductionTaskDao productionTaskDao;



    @Transactional
    @Override
    public Boolean saveProductionTechnology(Order order) {
        //返回值为影响的数据库行数
        int col1 = orderMapper.updateGoodsInfo(order);
        int col2 = orderMapper.updateOrderStatus(order);

        if (col1 == 1 && col2==1){
            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public List<String> calculateRawMaterialStock(Long orderId) {
        //根据orderId，找到产品信息及对应生产工艺，计算所需原材料量，与原材料库存对比
        List<String> messages = new ArrayList<>();
        Order order = orderDao.findById(orderId).get();
        //根据表中产品及对应生产工艺计算出所需原材料的库存
        String orderInfoStr = order.getGoodInfo();
        List<GoodsInfo> goodsInfos = JSON.parseArray(orderInfoStr, GoodsInfo.class);
        goodsInfos.forEach(goodsInfo -> {
            String tempPT = goodsInfo.getPt();

            String technology = ptDao.findFirstByName(tempPT).getTechnology();
            List<ProductionTechnologyDTO> ptList = JSON.parseArray(technology, ProductionTechnologyDTO.class);
            ptList.forEach(pt->{
                //访问原材料库存  计算库存量是否充足
                System.out.println(pt);
                Double currentRMCount = rawMaterialInventoryDao.findFirstByRawMaterialId(pt.getRM().getId()).getCount();
                String currentRMName = rawMaterialDao.findById(pt.getRM().getId()).get().getName();
                if (goodsInfo.getGoodsUnit().trim().equals("千克")) {
                    log.info("`````````````````````````````````````````kg");
                    if (goodsInfo.getGoodsNumber()* pt.getRMPercent()/100 <= currentRMCount){
                        messages.add("原材料："+ currentRMName +"充足") ;
                    } else {
                        messages.add("原材料："+ currentRMName +"还差" + (goodsInfo.getGoodsNumber()* pt.getRMPercent()/100 - currentRMCount));
                    }
                } else {
                    log.info("`````````````````````````````````````````pi");
                    if (goodsInfo.getGoodsNumber()*20* pt.getRMPercent()/100 <= currentRMCount){
                        messages.add("原材料："+ currentRMName +"充足") ;
                    } else {
                        messages.add("原材料："+ currentRMName +"还差" + (goodsInfo.getGoodsNumber()*20* pt.getRMPercent()/100 - currentRMCount));
                    }
                }
            });
        });
        Boolean adequate = true;
        for (String message : messages) {
            if (message.contains("还")){
                adequate = false;
            }
        }
        if (adequate) {
            //将订单状态改为2
            this.changeStatus(2,orderId);
        }
        return messages;
    }

    @Override
    public Boolean changeStatus(int status,Long id) {
        Order order = new Order();
        order.setOrderStatus(status);
        order.setId(id);
        return orderMapper.updateOrderStatus(order)==1;
    }

    @Override
    public List<RawMaterial> getRMByOrderId(Long orderId) {
        List<RawMaterial> list = new ArrayList<>();
        //根据orderID获取生产任务
        List<ProductionTask> tasks = productionTaskDao.findAllByOrderId(orderId);
        for (ProductionTask task : tasks) {
            //根据生产工艺获取原材料
            String technology = ptDao.findFirstByName(task.getPtName()).getTechnology();
            List<ProductionTechnologyDTO> ptList = JSON.parseArray(technology, ProductionTechnologyDTO.class);
            for (ProductionTechnologyDTO pt : ptList) {
                RawMaterial currentRM = pt.getRM();
                currentRM.setCooperativesName(task.getCooperativesName());
                list.add(currentRM);
            }
        }
        return list;
    }

    @Override
    public List<Order> getOrderList() {
        return orderDao.findAll();
    }

    @Override
    public Boolean addOrder(Order order) {
        Order save = orderDao.save(order);
        return save!=null;
    }




    @Override
    public Boolean update(Order order) {
        Order order1 = orderDao.findById(order.getId()).get();
        BeanUtils.copyProperties(order,order1);
        return orderDao.saveAndFlush(order1) != null;
    }

    @Override
    public Boolean add(Order order) {
        return orderDao.save(order) != null;
    }

    @Override
    @Transactional
    public Boolean deleteIds(Long[] ids) {
        return ServiceUtil.deleteIds(ids,orderDao);
    }

    @Override
    public List<Order> listPage(int page, int size) {
        return orderDao.findAll(PageRequest.of(page, size)).getContent();
    }

    @Override
    public List<Order> listPageLike(int page, int size, String column) {
        return orderDao.findAllByCustomerNameLike(StringUtil.addLike(column),PageRequest.of(page, size));
    }
}
